package com.sky.utils;

import com.sky.constant.MessageConstant;
import com.sky.exception.UploadException;
import com.sky.properties.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
@Component
public class MinioUtil {

    @Autowired
    private MinioProperties minioProperties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
        try{
            // 创建MinioClient对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            // 创建bucket
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            System.out.println(found);
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("bucket").build());
            } else {
                System.out.println("Bucket 'sky-take-out-bucket' already exits.");
            }
            // 获取上传名称
            // 1 每个上传文件名称唯一
            // 2 根据当前内容对上传文件进行分组

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            String filename = uuid + file.getOriginalFilename();
            // 文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                            .object(filename)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build());
            //获取上传文件在minio路径
            String url = minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + filename;
            return url;
        } catch (Exception e){
            e.printStackTrace();
            throw new UploadException(MessageConstant.UPLOAD_FAILED);
        }
    }
}
